﻿
Imports System.Threading
Imports osi.root.constants

<global_init(global_init_level.foundamental)>
Public Class control_c
    Public Shared Event press(ByRef cancel As Boolean)
    Private Shared _blocking As Int32
    Private Shared _pressed As Boolean

    Public Shared Function pressed() As Boolean
        Return _pressed
    End Function

    Public Shared Sub block()
        k_assert(Interlocked.Increment(_blocking) > 0)
    End Sub

    Public Shared Sub release()
        k_assert(Interlocked.Decrement(_blocking) >= 0)
    End Sub

    Public Shared Function blocking_count() As Int32
        Return _blocking
    End Function

    Public Shared Function blocking() As Int32
        Return blocking_count() > 0
    End Function

    Shared Sub New()
        _pressed = False
        AddHandler Console.CancelKeyPress,
                   Sub(sender As Object, arg As ConsoleCancelEventArgs)
                       RaiseEvent press(arg.Cancel())
                       If Not arg.Cancel() Then
                           _pressed = True
                           While blocking()
                               sleep()
                           End While
                       End If
                   End Sub
    End Sub

    Private Shared Sub init()
    End Sub
End Class
